package cn.edu.bupt.freewings.forum.front.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.bupt.freewings.forum.common.TopicType;
import cn.edu.bupt.freewings.forum.front.beans.UserBean;
import cn.edu.bupt.freewings.forum.front.utility.CommonUtility;
import cn.edu.bupt.freewings.forum.front.utility.TypeBuilder;
import cn.edu.bupt.freewings.forum.front.controller.ProjectController;
import cn.edu.bupt.freewings.forum.client.rest.TopicClient;

/**
 * @author hubaiyu (hubaiyu@gmail.com)
 * 
 */
public class NewTopicAction extends HttpServlet {

	public final static String PARAM_PROJECT_ID = "projectId";
	public final static String PARAM_TOPIC_NAME = "name";

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		UserBean user = CommonUtility.getUser(request, response);
		// Only logined user can open a topic
		if (user == null) {
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		Integer projectId = Integer.valueOf(request.getParameter(PARAM_PROJECT_ID));
		String topicName = (String) request.getParameter(PARAM_TOPIC_NAME);
		TopicType.Topic newTopic = TypeBuilder.makeTopic(topicName, user.getId(),
				projectId);
		new TopicClient().put(newTopic);
		String forwardPath = "project?" + ProjectController.PARAM_ID + "="
				+ projectId; 
		request.getRequestDispatcher(forwardPath).forward(request, response);
	}
}
